package org.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket {
    // 资源私有
    private int number = 30;
    private Lock lock =  new ReentrantLock();
    // 资源类对外暴露的调用方法
    public void saleTicket(){
        lock.lock();
        try {
            //  需要上锁的代码
            if (number >0 ) {
                System.out.println(Thread.currentThread().getName()+"\t卖出第:"+number--+"张票"+"\t 还剩下："+number+"张票");
            }
        } finally {
            lock.unlock();
        }
    }
}
public class ReentrantLockSaleTicket {
    public static void main( String[] args )
    {
        final Ticket ticket = new Ticket();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"B").start();
        // start()方法只是告诉操作系统 线程从new状态变成就绪状态（需要等待时间片和调度算法优先级等因素影响才能调度）
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        },"C").start();
    }
    //  线程的状态可以通过枚举类获取 Thread.State

}
